/**
 *   DataSlim - Lazy Loading Framework
 *   Copyright (C) 2007 Rodolfo Dias
 *   
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this program; if not, write to the Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * 
 */

package net.dataslim.invoke;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import net.dataslim.annotations.DataSlimReturn;

public class DataSlimInvocationHandler extends DataSlimResult implements InvocationHandler{

	private Object delegate;
	private Class delegateClass;

	public DataSlimInvocationHandler(Object delegate, Class interfaceClass)
	{
		this.delegate = delegate;
		this.delegateClass = delegate.getClass();
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
		throws Exception{
		try	{
			Method methodForInvoke = delegateClass.getMethod(method.getName(), (Class[])method
					.getParameterTypes());
			Object result = methodForInvoke.invoke(delegate, args);
			if (method.isAnnotationPresent(DataSlimReturn.class)){
				result = proxied(result);
			}
			return result;
		}catch (Throwable e){
			e.printStackTrace();
			throw new Exception("Erro:" + e.getMessage() + " Causado por: " + e.getCause());
		}
	}
	
	
}
